/**
 * 
 */
package com.pmsco.pms.util;

import java.util.ArrayList;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

/**
 * @author Long Tran
 *
 */
public class JQGridBuildWhereClause {
	private static ArrayList<Operator> endWithPercentOperator = new ArrayList<Operator>();
	private static ArrayList<Operator> startWithPercentOperator = new ArrayList<Operator>();
	private static ArrayList<Operator> startEndWithPercentOperator = new ArrayList<Operator>();
	
	private enum Operator {
		eq, //equal
		ne, //not equal
		lt, //less than
		le,	//less than or equal
		gt,	//greater than
		ge,	//greater than or equal
		bw,	//begin with
		bn,	//doesn't begin with
		in,	//is in
		ni,	//is not in
		ew,	//end with
		en,	//doesn't end with
		cn,	//contain
		nc; //doesn't contain
		
		public static Operator getByString(String oper) {
			Operator ret = null;
			for(Operator operator : Operator.values()) {
				if(oper.equals(operator.name())) {
					ret = operator;
					break;
				}
			}
			return ret;
		}
	}
	
	static {
		endWithPercentOperator.add(Operator.bw);
		endWithPercentOperator.add(Operator.bn);
		
		startWithPercentOperator.add(Operator.ew);
		startWithPercentOperator.add(Operator.en);
		
		startEndWithPercentOperator.add(Operator.cn);
		startEndWithPercentOperator.add(Operator.nc);
		startEndWithPercentOperator.add(Operator.in);
		startEndWithPercentOperator.add(Operator.ni);
	}
	
	public static Criterion getWhereClase(String col, String val, String oper) {
		Criterion ret = null;
		Operator operator = Operator.getByString(oper);
		if(operator != null) {
			if(endWithPercentOperator.contains(operator))
				val += "%";
			if(startWithPercentOperator.contains(operator))
				val = "%" + val;
			if(startEndWithPercentOperator.contains(operator))
				val = "%" + val + "%";
			
			switch(operator) {
				case eq:
					ret = Restrictions.eq(col, val);
					break;
				case ne:
					ret = Restrictions.ne(col, val);
					break;
				case lt:
					ret = Restrictions.lt(col, val);
					break;
				case le:
					ret = Restrictions.le(col, val);
					break;
				case gt:
					ret = Restrictions.gt(col, val);
					break;
				case ge:
					ret = Restrictions.ge(col, val);
					break;
				case bw:
				case in:
				case ew:
				case cn:
					ret = Restrictions.like(col, val);
					break;
				case bn:
				case ni:
				case en:
				case nc:
					ret = Restrictions.not(Restrictions.like(col, val));
					break;
			}
		}
		return ret;
	}
}
